#include "NeoSwitchButtonPrivate.h"
#include "NeoSwitchButton.h"
#include <QPropertyAnimation>

NeoSwitchButtonPrivate::NeoSwitchButtonPrivate(QObject *parent)
    : QObject(parent),
      pIndicatorRadius(0),
      pPosition(0),
      pChecked(true),
      pIndicatorCheckedColor(Qt::white),
      pIndicatorUncheckedColor(Qt::white),
      pBackgroundCheckedColor(Qt::blue),
      pBackgroundUncheckedColor(Qt::blue),
      pPositionAnimation(new QPropertyAnimation(this, "pPosition", this))
{
    pPositionAnimation->setDuration(200);
    pPositionAnimation->setEasingCurve(QEasingCurve::InOutQuad);
}

NeoSwitchButtonPrivate::~NeoSwitchButtonPrivate() = default;

void NeoSwitchButtonPrivate::startPositionAnimation()
{
    NEO_PRIVATE_POINT(NeoSwitchButton)
    if (pPositionAnimation->state() == QPropertyAnimation::Running)
    {
        return;
    }
    if (pChecked)
    {
        pPositionAnimation->setDirection(QPropertyAnimation::Forward);
    }
    else
    {
        pPositionAnimation->setDirection(QPropertyAnimation::Backward);
    }
    pPositionAnimation->setStartValue(0);
    pPositionAnimation->setEndValue(q->width() - q->height());
    pPositionAnimation->start();
}

void NeoSwitchButtonPrivate::updateWidgetGeometry(QSize size)
{
    pIndicatorRadius = size.height() / 2 - 2;
}

void NeoSwitchButtonPrivate::drawBackground(QPainter *painter)
{
    NEO_PRIVATE_POINT(NeoSwitchButton)
    painter->save();
    QRect rect = QRect(0, 0, q->width(), q->height()).adjusted(1, 1, -1, -1);
    qreal radius = rect.height() / 2.0;
    painter->setPen(pChecked ? pBackgroundCheckedColor : pBackgroundUncheckedColor);
    painter->setBrush(pChecked ? pBackgroundCheckedColor : pBackgroundUncheckedColor);
    painter->drawRoundedRect(rect, radius, radius);
    painter->restore();
}

void NeoSwitchButtonPrivate::drawIndicator(QPainter *painter)
{
    NEO_PRIVATE_POINT(NeoSwitchButton)
    painter->save();
    painter->setBrush(pChecked ? pIndicatorCheckedColor : pIndicatorUncheckedColor);
    QRect indicatorRect(
        q->height() / 2 - pIndicatorRadius + pPosition,
        q->height() / 2 - pIndicatorRadius,
        2 * pIndicatorRadius,
        2 * pIndicatorRadius);
    indicatorRect = indicatorRect.adjusted(0.5, 0.5, -0.5, -0.5);
    painter->drawEllipse(indicatorRect);
    painter->restore();
}
